import React, {useEffect, useLayoutEffect, useRef, useState} from "react";
import {Avatar, Container, CssBaseline, List, ListItemIcon, Paper} from "@mui/material";
import {useLocation} from "react-router-dom";
import {Box, Divider, Fab, Grid, ListItem, ListItemText, TextField, Typography} from "@material-ui/core";

import {avatars} from "../../roleImage";
import {Send} from "@material-ui/icons";
import Cookies from 'universal-cookie';

function SelfMessage(msg, index){
  return(
    <ListItem key={index} autoFocus={true}>
      <Grid container>
        <Grid item xs={12}>
          <ListItemText align='right' primary={msg.content}/>
        </Grid>
        <Grid item xs={12}>
          <ListItemText align='right' secondary={new Date(msg.time).toLocaleTimeString()}/>
        </Grid>
      </Grid>
      <Box sx={{m:1}}>
        <Avatar sx={{marginLeft:'8px'}} src={avatars[msg.user.roleType][msg.user.roleIndex]}/>
        <Typography variant='caption' noWrap>{msg.user.nickName}</Typography>
      </Box>
    </ListItem>
  )
}

function NormalMessage(msg, index){
  return(
    <ListItem key={index}>
      <Box sx={{m:1}}>
        <Avatar sx={{marginLeft:'8px'}} src={avatars[msg.user.roleType][msg.user.roleIndex]}/>
        <Typography variant='caption' noWrap>{msg.user.nickName}</Typography>
      </Box>
      <Grid container>
        <Grid item xs={12}>
          <ListItemText align='left' primary={msg.content}/>
        </Grid>
        <Grid item xs={12}>
          <ListItemText align='left' secondary={new Date(msg.time).toLocaleTimeString()}/>
        </Grid>
      </Grid>
    </ListItem>
  )
}

export default function Chat(){
  const location = useLocation();

  const [userInfo, setUserInfo] = useState({nickName:'NULL', roleType:'cats', roleIndex:0});
  const [room, setRoom] = useState('<Chat>');
  const [userList, setUserList] = useState([])
  const [msgList, setMsgList] = useState([])
  const [currentInput, setCurrentInput] = useState('');
  const ws = useRef(null);

  useLayoutEffect(()=>{
    setRoom(location.state.room)
    setUserInfo(location.state.userInfo)
  }, [])

  useEffect(()=>{
    const wss_protocol = (window.location.protocol === 'https:') ? 'wss://': 'ws://';
    const cookie = new Cookies();
    cookie.set('userInfo', location.state.userInfo)
    cookie.set('SameSite', 'Lax')
    const ws_url = wss_protocol + window.location.host + '/ws/chat/'  + encodeURI(location.state.room)
    console.log(ws_url)
    ws.current = new WebSocket(
      ws_url
    );
    ws.current.onopen = e=>{console.log(e)}
    ws.current.onmessage = e=>{
      const data = JSON.parse(e.data)
      if(data.type === 'chat_msg' || data.type === 'self'){
        setMsgList(msgList=>[...msgList, data])
      } else if(data.type === 'user_list'){
        setUserList(data.list)
      }
    }
  },[])

  // 滚动到最新消息
  const scrollRef = useRef(null);
  useEffect(()=>{
    scrollRef.current.scrollIntoView({ behaviour: "smooth" });
  },[msgList])

  function sendMessage(){
    ws.current.send(JSON.stringify(
      {
        'type': 'chat_msg',
        'payload': currentInput
      }
    ));
    setCurrentInput('');
  }

  return (
    <Container>
      <CssBaseline/>
      {/*房间标题*/}
      <Grid container>
        <Grid item xs={12} >
          <Typography variant="h5" >{room}</Typography>
        </Grid>
      </Grid>
      {/*聊天窗口*/}
      <Grid container component={Paper} sx={{height:'100%'}}>
        {/*用户列表*/}
        <Grid item xs={3} >
          <List>
            <ListItem button key={userInfo.nickName}>
              <ListItemIcon>
                <Avatar alt={userInfo.nickName} src={avatars[userInfo.roleType][userInfo.roleIndex]} />
              </ListItemIcon>
              <ListItemText primary={userInfo.nickName}/>
            </ListItem>
          </List>
          <Divider />
          <List>
            {userList.map((user)=>{
              return(
                <ListItem button>
                  <ListItemIcon>
                    <Avatar alt={user.nickName} src={avatars[user.roleType][user.roleIndex]} />
                  </ListItemIcon>
                  <ListItemText primary={user.nickName}>primary={user.nickName}</ListItemText>
                  <ListItemText secondary={user.joinTime} align='right'/>
                </ListItem>
              )
            })}
          </List>
        </Grid>
        <Grid item xs={9}>
          <List sx={{maxHeight:800, height:800,
            overflow: 'auto',}}>
            {msgList.map((msg, index)=>{
              if(msg.type === 'self'){
                return SelfMessage(msg, index)
              } else if(msg.type === 'chat_msg') {
                return NormalMessage(msg, index)
              }
            })}
            <ListItem ref={scrollRef} />
          </List>
          <Divider />
          <Grid container style={{padding: '20px'}}>
            <Grid item xs={11}>
              <TextField label="Type Something" value={currentInput} onChange={(event)=>{setCurrentInput(event.target.value)}} fullWidth />
            </Grid>
            <Grid xs={1} align="right">
              <Fab color="primary" onClick={sendMessage} aria-label="add"><Send/></Fab>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Container>
  )
}